package light.mvc.service.sys.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import light.mvc.dao.BaseDaoI;
import light.mvc.framework.constant.GlobalConstant;
import light.mvc.model.sys.Torganization;
import light.mvc.model.sys.Tresource;
import light.mvc.model.sys.Trole;
import light.mvc.model.sys.Tuser;
import light.mvc.model.workflow.Tform;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.base.SessionInfo;
import light.mvc.pageModel.sys.User;
import light.mvc.service.sys.UserServiceI;
import light.mvc.utils.DateUtils;
import light.mvc.utils.MD5Util;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements UserServiceI {
	@Resource
	private HibernateTemplate hibernateTemplate;
	@Autowired
	private BaseDaoI<Tuser> userDao;

	@Autowired
	private BaseDaoI<Trole> roleDao;
	
	@Autowired
	private BaseDaoI<Tform> formDao;

	@Autowired
	private BaseDaoI<Torganization> organizationDao;

	@Override
	public void add(User u) {
		Tuser t = new Tuser();
		BeanUtils.copyProperties(u, t);
		t.setIsdefault(1);
		t.setOrganization(organizationDao.get(Torganization.class, u.getOrganizationId()));

		t.setSuperior(userDao.get(Tuser.class, u.getSuperiorId()));

		List<Trole> roles = new ArrayList<Trole>();
		if (u.getRoleIds() != null) {
			for (String roleId : u.getRoleIds().split(",")) {
				roles.add(roleDao.get(Trole.class, Long.valueOf(roleId)));
			}
		}
		t.setRoles(new HashSet<Trole>(roles));

		t.setPassword(MD5Util.md5(u.getPassword()));
		t.setState(GlobalConstant.ENABLE);
		t.setCreatedatetime(new Date());
		userDao.save(t);
	}

	@Override
	public void delete(Long id) {
		Tuser t = userDao.get(Tuser.class, id);
		del(t);
	}

	private void del(Tuser t) {
		userDao.delete(t);
	}

	@Override
	public void edit(User user) {
		Tuser t = userDao.get(Tuser.class, user.getId());
		t.setAge(user.getAge());
		t.setLoginName(user.getLoginName());
		t.setName(user.getName());
		t.setMailBox(user.getMailBox());
		t.setOrganization(organizationDao.get(Torganization.class, user.getOrganizationId()));

		t.setSuperior(userDao.get(Tuser.class, user.getSuperiorId()));

		List<Trole> roles = new ArrayList<Trole>();
		if (user.getRoleIds() != null) {
			for (String roleId : user.getRoleIds().split(",")) {
				roles.add(roleDao.get(Trole.class, Long.valueOf(roleId)));
			}
		}
		t.setRoles(new HashSet<Trole>(roles));
		t.setSex(user.getSex());
		t.setUsertype(user.getUsertype());
		if (user.getPassword() != null && !"".equals(user.getPassword())) {
			t.setPassword(MD5Util.md5(user.getPassword()));
		}
		userDao.update(t);
	}

	@Override
	public User get(Long id) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		Tuser t = userDao.get("from Tuser t  left join fetch t.roles role where t.id = :id", params);
		User u = new User();
		BeanUtils.copyProperties(t, u);

		if (t.getOrganization() != null) {
			u.setOrganizationId(t.getOrganization().getId());
			u.setOrganizationName(t.getOrganization().getName());
		}

		if (t.getRoles() != null && !t.getRoles().isEmpty()) {
			String roleIds = "";
			String roleNames = "";
			boolean b = false;
			for (Trole role : t.getRoles()) {
				if (b) {
					roleIds += ",";
					roleNames += ",";
				} else {
					b = true;
				}
				roleIds += role.getId();
				roleNames += role.getName();
			}
			u.setRoleIds(roleIds);
			u.setRoleNames(roleNames);
		}
		return u;
	}

	@Override
	public User login(User user) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("loginName", user.getLoginName());
		params.put("password", MD5Util.md5(user.getPassword()));
		Tuser t = userDao.get("from Tuser t where t.loginName = :loginName and t.password = :password", params);
		if (t != null) {
			User u = new User();
			BeanUtils.copyProperties(t, u);
			return u;
		}
		return null;
	}

	@Override
	public List<String> resourceList(Long id) {
		List<String> resourceList = new ArrayList<String>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		Tuser t = userDao.get("from Tuser t join fetch t.roles role join fetch role.resources resource where t.id = :id", params);
		if (t != null) {
			Set<Trole> roles = t.getRoles();
			if ((roles != null) && !roles.isEmpty()) {
				for (Trole role : roles) {
					Set<Tresource> resources = role.getResources();
					if ((resources != null) && !resources.isEmpty()) {
						for (Tresource resource : resources) {
							if ((resource != null) && (resource.getUrl() != null)) {
								resourceList.add(resource.getUrl());
							}
						}
					}
				}
			}
		}
		return resourceList;
	}

	@Override
	public List<User> dataGrid(User user, PageFilter ph) {
		List<User> ul = new ArrayList<User>();
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from Tuser t ";
		List<Tuser> l = userDao.find(hql + whereHql(user, params) + orderHql(ph), params, ph.getPage(), ph.getRows());
		for (Tuser t : l) {
			User u = new User();
			BeanUtils.copyProperties(t, u);
			Set<Trole> roles = t.getRoles();
			if ((roles != null) && !roles.isEmpty()) {
				String roleIds = "";
				String roleNames = "";
				boolean b = false;
				for (Trole tr : roles) {
					if (b) {
						roleIds += ",";
						roleNames += ",";
					} else {
						b = true;
					}
					roleIds += tr.getId();
					roleNames += tr.getName();
				}
				u.setRoleIds(roleIds);
				u.setRoleNames(roleNames);
			}
			if (t.getOrganization() != null) {
				u.setOrganizationId(t.getOrganization().getId());
				u.setOrganizationName(t.getOrganization().getName());
			}
			if (t.getSuperior() != null) {
				u.setSuperiorId(t.getSuperior().getId());
				u.setSuperiorName(t.getSuperior().getName());
			}
			ul.add(u);
		}
		return ul;
	}

	@Override
	public Long count(User user, PageFilter ph) {
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from Tuser t ";
		return userDao.count("select count(*) " + hql + whereHql(user, params), params);
	}

	private String whereHql(User user, Map<String, Object> params) {
		String hql = "";
		if (user != null) {
			hql += " where 1=1 ";
			if (user.getName() != null) {
				hql += " and t.name like :name";
				params.put("name", "%%" + user.getName() + "%%");
			}
			if (user.getOrganizationId() != null) {
				hql += " and t.organization.id =" + user.getOrganizationId();
			}
		}
		return hql;
	}

	private String orderHql(PageFilter ph) {
		String orderString = "";
		if ((ph.getSort() != null) && (ph.getOrder() != null)) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}

	@Override
	public boolean editUserPwd(SessionInfo sessionInfo, String oldPwd, String pwd) {
		Tuser u = userDao.get(Tuser.class, sessionInfo.getId());
		if (u.getPassword().equalsIgnoreCase(MD5Util.md5(oldPwd))) {// 说明原密码输入正确
			u.setPassword(MD5Util.md5(pwd));
			return true;
		}
		return false;
	}

	@Override
	public User getByLoginName(User user) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("loginName", user.getLoginName());
		// Tuser t = userDao.get("from Tuser t  where t.loginName = '"+user.getLoginName()+"'");
		Tuser t = userDao.get("from Tuser t  where t.loginName = :loginName", params);
		User u = new User();
		if (t != null) {
			BeanUtils.copyProperties(t, u);
		} else {
			return null;
		}
		return u;
	}

	@Override
	public Tuser getTuserByLoginName(User user) {
		// Tuser t = userDao.get("from Tuser t  where t.loginName = '"+user.getLoginName()+"'");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("loginName", user.getLoginName());
		Tuser t = userDao.get("from Tuser t  where t.loginName = :loginName", params);
		return t;
	}

	@Override
	public List<User> getAllUser() {
		List<Tuser> tusers = userDao.findTuserBySql("select * from sys_user t order by CONVERT(t.name USING gbk)");
		List<User> users = new ArrayList<User>();
		for (Tuser tuser : tusers) {
			User user = new User();
			BeanUtils.copyProperties(tuser, user);
			users.add(user);
		}
		return users;
	}
	
	@Override
	public List<User> getInferiors(String loginId) {
		List<Tuser> tusers = userDao.findTuserBySql("select * from sys_user t where t.superiorId = " + loginId + " order by CONVERT(t.name USING gbk)");
		List<User> users = new ArrayList<User>();
		for (Tuser tuser : tusers) {
			User user = new User();
			BeanUtils.copyProperties(tuser, user);
			users.add(user);
		}
		return users;
	}

	public boolean isInferior(String inforiorLoginName, Long loginId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("inforiorLoginName", inforiorLoginName);
		params.put("loginId", loginId);
		List<Tuser> tusers = userDao.find(" from Tuser t where t.loginName = :inforiorLoginName and t.superior.id = :loginId", params);
		if (tusers != null && tusers.size() != 0) {
			return true;
		}
		return false;
	}

	@Override
	public List<User> getAllUserStatus() {
//		List<Tuser> tusers = userDao.find("from Tuser t where t.status in ('" + Tuser.STATUS_HOLIDAY + "','" + Tuser.STATUS_OUTGOING + "')");
		List<Tform> tfroms = formDao.findTformBySql("SELECT * FROM workflow_form t where t.status = '已通过' and curdate() <= left(t.startTime , 10) || left(t.endTime , 10) > curdate();");
		
		List<User> users = new ArrayList<User>();
		for (Tform tform : tfroms) {
			User user = new User();
			BeanUtils.copyProperties(tform.getApplicant(), user);
			user.setRegister(tform.getRegister());
			user.setStartTime(tform.getStartTime());
			user.setEndTime(tform.getEndTime());
			users.add(user);
		}
		return users;
	}

	@Override
	public void myUpdate(User user) {
		Tuser tuser = userDao.get(Tuser.class, user.getId());
		tuser.setStatus(user.getStatus());
		userDao.update(tuser);
	}

	/**
	 * @return
	 */
	private DetachedCriteria getCriteria() {
		return DetachedCriteria.forClass(Tuser.class);
	}

	@Override
	public List<List<User>> showPeopleHolidayStatus() throws ParseException {
//		Map<String, Object> params = new HashMap<String, Object>();
//		params.put("status", "休假");
//		List<Tuser> tusers = userDao.find("from Tuser t  where t.status = :status", params);
		List<Tform> tfroms = formDao.findTformBySql("SELECT * FROM workflow_form t where t.status = '已通过' and (curdate() <= left(t.startTime , 10) || left(t.endTime , 10) > curdate());");
		
		List<List<User>> usersOfAll = new ArrayList<List<User>>();
		List<User> usersOfToday = new ArrayList<User>();
		List<User> usersOfTomorrow = new ArrayList<User>();
		List<User> usersOfAfterTomorrow = new ArrayList<User>();
		for (Tform tform : tfroms) {
			User user = new User();

			String startTime = tform.getStartTime();
			String dateStartStr = startTime.substring(0, 10);
			Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateStartStr);

			String endTime = tform.getEndTime();
			String dateEndStr = endTime.substring(0, 10);
			Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateEndStr);

			Date dateNow = new SimpleDateFormat("yyyy-MM-dd").parse(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

			Date dateTomorrow = new SimpleDateFormat("yyyy-MM-dd").parse(new SimpleDateFormat("yyyy-MM-dd").format(DateUtils.getSpecifiedDayAfter(new Date())));

			Date dateAfterTomorrow = new SimpleDateFormat("yyyy-MM-dd").parse(new SimpleDateFormat("yyyy-MM-dd").format(DateUtils.getSpecifiedDayAfter(DateUtils.getSpecifiedDayAfter(new Date()))));
			
			user.setRegister(tform.getRegister());
			user.setStartTime(tform.getStartTime());
			user.setEndTime(tform.getEndTime());
			
			// 休假起始时间小于当前时间 且 休假截止时间大于当前时间
			if (startDate.compareTo(dateNow) <= 0 && endDate.compareTo(dateNow) >= 0) {
				BeanUtils.copyProperties(tform.getApplicant(), user);
				usersOfToday.add(user);
			}
			if (startDate.compareTo(dateTomorrow) <= 0 && endDate.compareTo(dateTomorrow) >= 0) {
				BeanUtils.copyProperties(tform.getApplicant(), user);
				usersOfTomorrow.add(user);
			}
			if (startDate.compareTo(dateAfterTomorrow) <= 0 && endDate.compareTo(dateAfterTomorrow) >= 0) {
				BeanUtils.copyProperties(tform.getApplicant(), user);
				usersOfAfterTomorrow.add(user);
			}
		}
		usersOfAll.add(usersOfToday);
		usersOfAll.add(usersOfTomorrow);
		usersOfAll.add(usersOfAfterTomorrow);
		return usersOfAll;
	}

	public static void main(String[] args) throws ParseException {
		Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2014-7-30");
		Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date2));
		System.out.println(date.compareTo(date2));
	}
}
